<?php
/**
* Django's templating engine (partial) PHP implementation.
* this is the <q>include</q> tag class
* supports additional aliases arguments
* to set alias to context when rendering included templates
* {% include template alias=var alias2=var2 }
* template may be a var or a quoted literal
* @link http://djangoproject.com
* this file is from a webappkit package (kit)
* @link http://webappkit.net
* @package djtpl
* @author J.Ducastel <nospam0@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class DjTplTagNode_include extends DjTplTagNode {

    /**
     * @var string template to include
     */
    var $include_id;

    /**
     * @var array alias => key
     */
    var $aliases=array();

    /**
    * builds itself from tokens
    * @param djangoTplToken &$selfToken
    * @param array &$nextTokens djangoTplToken
    * @access public
    * @return bool
    */
    function buildFromTokens(&$selfToken,&$nextTokens) {
        $def=$selfToken->tagdef;
        $regex='("?[a-zA-Z0-9\._-]+"?)( [a-zA-Z0-9\._]+=[a-zA-Z0-9\._]+)*';
        if (ereg($regex,$def,$search)) {
            $this->include_id=next($search);
            while ($str=next($search)) {
                $parsed=explode('=',substr($str,1));
                $this->aliases[$parsed[0]]=$parsed[1];
            }
        } else {
            // error !
            trigger_error('invalid structure for tag include : '.$def);
        }
        // $this->buildChildNodesFromTokens($nextTokens);
        // echo '<pre>'; print_r($this);
        return true;
    }

    /**
     * the tag hasn't to be closed
     */
    function isAtomic() {
        return true;
    }

    /**
    * renders as string
    * @param djangoTplContext $context
    * @access public
    * @return string
    */
    function render(&$context) {
        // return "<p>including {$this->include_id}</p>";
        // evaluating template id
        $id=DjTplParser::evalExpression($context,$this->include_id); // echo $id;
        // getting template
        if (!$tpl=&$this->getTplFromStorage($id)) {
            // print_r($template);
            return '<!--failed to include '.$id.' -->';
        }
        // setting aliases
        foreach ($this->aliases as $alias => $key) {
            $context->setPathAlias($key,$alias);
        } // print_r($context);
        return $tpl->render($context);
    }

    /**
     * get template from current storage
     */
    function getTplFromStorage($id) {
        // echo '<pre>'; print_r($this);
        //$storage=DjTplStorage::getCurrent();
        $storage=$this->template->getStorage();
        return $storage->get($id);
    }/**/
}
